package com.server.questionbank.snframe.service.CourseService.Impl;

import com.server.questionbank.snframe.controller.Course.pojo.AddExercises;
import com.server.questionbank.snframe.controller.Course.pojo.Exercises.UpdateExercises;
import com.server.questionbank.snframe.domain.Homework.TExercises;
import com.server.questionbank.snframe.domain.QuestionBank.Question;
import com.server.questionbank.snframe.domain.ResDTO.PageResult;
import com.server.questionbank.snframe.domain.Course.TKnowledge;
import com.server.questionbank.snframe.mapper.Course.TExercisesMapper;
import com.server.questionbank.snframe.service.CourseService.TExerciseService;
import com.server.questionbank.snframe.service.CourseService.TQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TExerciseServiceImpl implements TExerciseService {
    @Autowired
    private TExercisesMapper tExercisesMapper;
    @Autowired
    private TQuestionService tQuestionService;

    // 获取所有题目
    @Override
    public PageResult<TExercises> getAllExercises(String sortField, String sortDirection, Long pageNum, Long pageSize) {
        if (sortField == null || sortField.isEmpty()) sortField = "exercises_id";
        if (sortDirection == null || sortDirection.isEmpty()) sortDirection = "ASC";
        if (pageNum == null || pageNum <= 0) pageNum = 1L;
        if (pageSize == null || pageSize <= 0) pageSize = 1L;
        pageSize = Math.min(pageSize, 1000L);
        Long offset = pageSize * (pageNum - 1L);
        return new PageResult<>(
                tExercisesMapper.queryExercises(null, null, null, null, null, null,
                        sortField, sortDirection, offset, pageSize),
                tExercisesMapper.queryCountExercises(null, null, null, null, null, null),
                pageNum, pageSize
        );
    }

    // 获取所有指定类型的题目
    private PageResult<TExercises> getAllTypeExercises(String type, String sortField, String sortDirection, Long pageNum, Long pageSize) {
        if (sortField == null || sortField.isEmpty()) sortField = "exercises_id";
        if (sortDirection == null || sortDirection.isEmpty()) sortDirection = "ASC";
        if (pageNum == null || pageNum <= 0) pageNum = 1L;
        if (pageSize == null || pageSize <= 0) pageSize = 1L;
        pageSize = Math.min(pageSize, 1000L);
        Long offset = pageSize * (pageNum - 1L);
        return new PageResult<>(
                tExercisesMapper.queryExercises(null, null, null, null, null, type,
                        sortField, sortDirection, offset, pageSize),
                tExercisesMapper.queryCountExercises(null, null, null, null, null, type),
                pageNum, pageSize
        );
    }

    // 获取所有课程题目
    @Override
    public PageResult<TExercises> getAllCourseExercises(String sortField, String sortDirection, Long pageNum, Long pageSize) {
        return getAllTypeExercises("course", sortField, sortDirection, pageNum, pageSize);
    }
    // 获取所有竞赛题目
    @Override
    public PageResult<TExercises> getAllCompetitionExercises(String sortField, String sortDirection, Long pageNum, Long pageSize) {
        return getAllTypeExercises("competition", sortField, sortDirection, pageNum, pageSize);
    }

    // 根据 exercisesId 查询题目
    @Override
    public TExercises getExercisesById(Long exercisesId) {
        List<TExercises> result = tExercisesMapper.queryExercises(exercisesId, null, null, null, null,
                null, null, null, null, null);
        return result.isEmpty() ? null : result.get(0);
    }

    // 根据 knowledgeId 查询题目
    @Override
    public PageResult<TExercises> getExercisesByKnowledgeId(Long knowledgeId, String sortField, String sortDirection, Long pageNum, Long pageSize) {
        if (sortField == null || sortField.isEmpty()) sortField = "exercises_id";
        if (sortDirection == null || sortDirection.isEmpty()) sortDirection = "DESC";
        if (pageNum == null || pageNum <= 0) pageNum = 1L;
        if (pageSize == null || pageSize <= 0) pageSize = 1L;
        pageSize = Math.min(pageSize, 1000L);
        Long offset = pageSize * (pageNum - 1L);
        return new PageResult<>(
                tExercisesMapper.queryExercises(null, knowledgeId, null, null, null, null,
                        sortField, sortDirection, offset, pageSize),
                tExercisesMapper.queryCountExercises(null, knowledgeId, null, null, null, null),
                pageNum, pageSize
        );
    }

    // 根据 courseId 查询题目
    @Override
    public PageResult<TExercises> getExercisesByCourseId(Long courseId, Boolean noChapter, String sortField, String sortDirection, Long pageNum, Long pageSize) {
        if (sortField == null || sortField.isEmpty()) sortField = "exercises_id";
        if (sortDirection == null || sortDirection.isEmpty()) sortDirection = "DESC";
        if (pageNum == null || pageNum <= 0) pageNum = 1L;
        if (pageSize == null || pageSize <= 0) pageSize = 1L;
        pageSize = Math.min(pageSize, 1000L);
        Long offset = pageSize * (pageNum - 1L);
        return new PageResult<>(
                tExercisesMapper.queryExercises(null, null, courseId, noChapter, null, null,
                        sortField, sortDirection, offset, pageSize),
                tExercisesMapper.queryCountExercises(null, null, courseId, noChapter, null, null),
                pageNum, pageSize
        );
    }

    // 根据 chapterId 查询题目
    @Override
    public PageResult<TExercises> getExercisesByChapterId(Long chapterId, String sortField, String sortDirection, Long pageNum, Long pageSize) {
        if (sortField == null || sortField.isEmpty()) sortField = "exercises_id";
        if (sortDirection == null || sortDirection.isEmpty()) sortDirection = "ASC";
        if (pageNum == null || pageNum <= 0) pageNum = 1L;
        if (pageSize == null || pageSize <= 0) pageSize = 1L;
        pageSize = Math.min(pageSize, 1000L);
        Long offset = pageSize * (pageNum - 1L);
        return new PageResult<>(
                tExercisesMapper.queryExercises(null, null, null, null, chapterId, null,
                        sortField, sortDirection, offset, pageSize),
                tExercisesMapper.queryCountExercises(null, null, null, null, chapterId, null),
                pageNum, pageSize
        );
    }

    // 添加题目
    @Override
    public Long addExercises(AddExercises exercises) {
        tExercisesMapper.addExercises(exercises);
        return exercises.getExercisesId();
    }

    // 添加知识点
    @Override
    public Long addKnowledge(Long exercisesId, List<TKnowledge> knowledges) {
        if (knowledges == null || knowledges.isEmpty()) return 1L;
        return tExercisesMapper.addKnowledge(exercisesId, knowledges);
    }

    // 清空知识点
    @Override
    public Boolean clearKnowledge(Long exercisesId) {
        return tExercisesMapper.clearKnowledge(exercisesId) > 0;
    }

    // 修改题目
    @Override
    public Boolean updateExercises(UpdateExercises exercises) {
        try {
            // 更新题目
            if(tExercisesMapper.updateExercises(exercises) <= 0) return false;
            // 清空知识点
            clearKnowledge(exercises.getExercisesId());

            // 转换知识点数据
            List<TKnowledge> tkList = exercises.getKnowledges().stream()
                    .map(uk -> uk.toTKnowledge()) // 或使用工具类转换
                    .collect(Collectors.toList());
            if(addKnowledge(exercises.getExercisesId(), tkList) <= 0) return false;

            // 更新题目问题
            // 获取当前问题列表
            List<Question> tqList = tQuestionService.getQuestionByExercisesId(exercises.getExercisesId());
            // 新的问题列表
            List<Question> newQuestionList = exercises.getQuestions().stream().map(q -> q.toQuestion()).collect(Collectors.toList());

            // 获取需要添加的问题
            List<Question> toAdd = newQuestionList.stream()
                    .filter(q -> q.getRecId() == null || tqList.stream().noneMatch(old -> old.getRecId().equals(q.getRecId())))
                    .map(q -> {
                        q.setExercisesId(exercises.getExercisesId());
                        return q;
                    })
                    .collect(Collectors.toList());
            if(!tQuestionService.addQuestion(toAdd)) return false;

            // 获取需要更新的问题
            List<Question> toUpdate = newQuestionList.stream()
                    .filter(newQ -> newQ.getRecId() != null)
                    .filter(newQ -> tqList.stream()
                            .anyMatch(oldQ -> oldQ.getRecId().equals(newQ.getRecId()))
                    )
                    .map(q -> {
                        q.setExercisesId(exercises.getExercisesId());
                        return q;
                    })
                    .collect(Collectors.toList());
            if(!tQuestionService.updateQuestion(toUpdate)) return false;

            // 获取需要删除的问题
            List<Long> toDelete = tqList.stream()
                    .filter(oldQ -> newQuestionList.stream()
                            .noneMatch(newQ -> oldQ.getRecId().equals(newQ.getRecId())))
                    .map(oldQ -> oldQ.getRecId())
                    .collect(Collectors.toList());
            if(!tQuestionService.deleteQuestion(toDelete)) return false;

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
